import axios from 'axios'
import Vue from 'vue'
// 配置api地址
const baseURL = '/api'

// axios设置
const $ajax = axios.create({
  baseURL,
  timeout: 20000,
  withCredentials: true
})
//判断是否是开发模式
if(process.env.NODE_ENV === 'development') {
	window.localStorage.setItem('log', 'true')
}

/* 屏蔽console.log */
let tempLog = window.console.log
if(window.localStorage.getItem('log') === 'true') {
	window.console.log = tempLog
} else {
	window.console.log = () => null
}

/* 拦截器 */
$ajax.interceptors.request.use(function (config) {
  //获取token
  let usertoken = window.sessionStorage.getItem("usertoken")
	let latticeid = window.sessionStorage.getItem('latticeid')
	let organid = window.sessionStorage.getItem('organid')

  config.headers.userkey = usertoken;
	config.headers.latticeId = latticeid
	config.headers.organId = organid

	/* if(usertoken){
	 // config.data['userkey'] = usertoken
	 config.data['latticeId'] = latticeid
	} */
  return config
	
}, function (error) {
  // 当出现请求错误是做一些事
  console.log('--请求出错--', error)
	console.log(this,'this')
  return Promise.reject(error)
})
let timeOut = null
// 添加一个返回拦截器
$ajax.interceptors.response.use(function (response) {
	// console.log(response,'response')
	clearTimeout(timeOut)
	timeOut = setTimeout(() => {
		// Vue.prototype.$alert('出错','Go Home')
		// console.log(Vue.prototype.$alert,'this')
		if(response.data.code == 3 || response.data.code == 2 || response.data.code == 4) {
			// 3代表用户没有访问菜单权限 2代表登录已经超时 msg提示
			Vue.prototype.$alert('', response.data.msg, {
				confirmButtonText: '重新登录',
				showClose:false,
				center: true,
				callback: action => {
					// return window.location.href = window.location.origin
					return window.location.href = 'index.html'
				}
			
			});
		}
	},500)
  return response
}, function (error) {
  console.log('--返回出错--', error)
  // 对返回的错误进行一些处理
  return Promise.reject(error)
})

export default $ajax
